package cn.zhiwen.wxcontroller;

import cn.zhiwen.commonurl.CommonData;
import cn.zhiwen.util.SpellData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class MessageController {

    @RequestMapping("/wx")
    public String getMessage(HttpServletRequest request){
        Map<String, String> messageMap = xmlToMap(request);
        String s = messageMap.get(CommonData.content);
        System.out.println(s);
        switch (s){
            case "1":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"吴志文太帅了");
                break;
            case "2":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"吴志文老婆是荣荣");
                break;
            case "3":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"荣荣老公是吴志文");
                break;
            case "4":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"aaa");
                break;
            case "5":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"bbb");
                break;
            case "6":
                messageMap.put(CommonData.format,"text");
                messageMap.put(CommonData.content,"吴志文太帅了");
                break;
            default:
                messageMap.put("Content","请输入1然后2。。。。。");
        }

        System.out.println(SpellData.spellMessage(messageMap));
        return SpellData.spellMessage(messageMap);
    }

    /**
     * 将xml转化为Map集合
     *
     * @param request
     * @return
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked")
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        try {
            ins.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return map;
    }
}
